import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QGridLayout,
                             QPushButton, QLineEdit, QVBoxLayout)


class Calculator(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.reset()

    def initUI(self):
        self.setWindowTitle('简单计算器')

        # 创建显示框
        self.display = QLineEdit('0')
        self.display.setReadOnly(True)

        # 创建按钮
        buttons = [
            '7', '8', '9', '/',
            '4', '5', '6', '*',
            '1', '2', '3', '-',
            '0', '.', '=', '+',
            'C'
        ]

        # 创建网格布局
        grid = QGridLayout()
        grid.addWidget(self.display, 0, 0, 1, 4)

        positions = [(i + 1, j) for i in range(5) for j in range(4)]

        for position, button_text in zip(positions, buttons):
            if button_text == '':
                continue
            button = QPushButton(button_text)
            button.clicked.connect(self.on_button_click)
            grid.addWidget(button, *position)

        # 设置主布局
        main_layout = QVBoxLayout()
        main_layout.addWidget(self.display)
        main_layout.addLayout(grid)
        self.setLayout(main_layout)

        self.show()

    def reset(self):
        self.current = '0'
        self.operation = None
        self.previous = None
        self.waiting_for_operand = True

    def on_button_click(self):
        button = self.sender()
        text = button.text()

        if text.isdigit() or text == '.':
            if self.waiting_for_operand:
                self.current = text
                self.waiting_for_operand = False
            else:
                if text == '.' and '.' in self.current:
                    return
                self.current += text
        elif text in ['+', '-', '*', '/']:
            if self.previous is not None and not self.waiting_for_operand:
                self.calculate()
            self.operation = text
            self.previous = float(self.current)
            self.waiting_for_operand = True
        elif text == '=':
            if self.previous is not None and not self.waiting_for_operand:
                self.calculate()
                self.operation = None
                self.previous = None
                self.waiting_for_operand = True
        elif text == 'C':
            self.reset()

        self.display.setText(self.current)

    def calculate(self):
        if self.operation == '+':
            self.current = str(self.previous + float(self.current))
        elif self.operation == '-':
            self.current = str(self.previous - float(self.current))
        elif self.operation == '*':
            self.current = str(self.previous * float(self.current))
        elif self.operation == '/':
            try:
                self.current = str(self.previous / float(self.current))
            except ZeroDivisionError:
                self.current = '错误'

        # 移除不必要的 .0
        if '.' in self.current:
            self.current = self.current.rstrip('0').rstrip('.')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    calc = Calculator()
    sys.exit(app.exec_())